from __future__ import absolute_import
import logging
from forest.api import Command, get_tool
from os.path import join

logger = logging.getLogger('commands.files.Modify')

copy = get_tool('system.copy')

import re

class Modify(Command):
    ''' Matches and replaces file content based on the relevant resource definition.
    '''
    __register__ = 'commands.files.Modify'

    def run(self, config):
        install_tree = config.get_install_root()
        args = config.get('modify', False)

        if not args:
            return

        for modification in args:

            filename = modification.get('file')
            fulldestpath = [install_tree] + filename.split('/')
            fulldestpath = join(*fulldestpath)

            Command.SIGNAL_COMMAND_PROGRESS(self, message='Modifying %s' % (fulldestpath))

            outlines = self.run_modification(modification, fulldestpath)


            f = open(fulldestpath,'w')
            f.write('\n'.join(outlines))
            f.close()


    @staticmethod
    def run_modification(modification, filename):
        outlines = []
        f = open(filename, 'r')

        replacement = modification.get('replace')

        if 'match' in modification:
            match = modification.get('match')
            for line in f.readlines():
                if line.find(match) != -1:
                    outlines.append(line.replace(match, replacement))
                else:
                    outlines.append(line)
        elif 're' in modification:
            pattern = re.compile(modification.get('re'))
            outlines = pattern.sub(f.read(), line)
            return outlines.split('\n')
        else:
            raise Exception("Undefined matching.")

        f.close()

        return outlines
